using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using System.Timers;
using Application.Service.LogCache;

namespace Application.Web.Entry.Pages;

public partial class Index : ComponentBase, IDisposable
{
    // 实时时间
    private string CurrentTime { get; set; } = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss");
    
    // 计算后的高度值
    private string calculatedHeight { get; set; } = "auto";
    
    // 定时器
    private System.Timers.Timer? _timer;
    
    // JavaScript返回的高度计算结果类
    private class HeightResult
    {
        public string height { get; set; } = "600px";
        public int viewportHeight { get; set; }
        public int containerTop { get; set; }
        public int containerBottom { get; set; }
        public int footerTop { get; set; }
        public string reason { get; set; } = "";
    }

    // 大地坐标系参数
    private string AzimuthGuide { get; set; } = "0.000";
    private string ElevationGuide { get; set; } = "0.000";
    private string OffsetA { get; set; } = "0.000";
    
    private string AzimuthCurrent { get; set; } = "0.000";
    private string ElevationCurrent { get; set; } = "0.000";
    private string OffsetE { get; set; } = "0.000";

    // 转台坐标系参数
    private string AzimuthCommand { get; set; } = "0.000";
    private string ElevationCommand { get; set; } = "0.000";
    private string TiltCommand { get; set; } = "0.000";
    
    private string TiltCurrent { get; set; } = "0.000";
    
    private string AzimuthSpeed { get; set; } = "0.000";
    private string ElevationSpeed { get; set; } = "0.000";
    private string TiltSpeed { get; set; } = "0.000";



    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            // 初始化定时器更新时间
            _timer = new System.Timers.Timer(1000);
            _timer.Elapsed += async (sender, e) =>
            {
                await UpdateCurrentTime();
            };
            _timer.Start();

            // 初始更新时间
            await UpdateCurrentTime();

            // 计算高度值
            await CalculateHeight();
        }
    }

    private async Task UpdateCurrentTime()
    {
        try
        {
            var now = DateTime.Now;
            CurrentTime = now.ToString("yyyy年MM月dd日 HH:mm:ss");
            
            // 通知UI更新
            await InvokeAsync(StateHasChanged);
        }
        catch (Exception)
        {
            // 忽略异常，避免应用崩溃
        }
    }

    /// <summary>
    /// 计算LogDrawer容器的可用高度
    /// </summary>
    /// <returns></returns>
    private async Task CalculateHeight()
    {
        try
        {
            // 使用CancellationTokenSource设置超时
            using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));

            // 使用JavaScript计算LogDrawer容器的可用高度
            var jsCode = @"
                (function() {
                    return new Promise((resolve) => {
                        const calculateHeight = () => {
                            // 获取LogDrawer容器的父元素
                            const drawerContainer = document.querySelector('.layout-drawer-body');
                            if (!drawerContainer) {
                                resolve({ height: '600px', reason: '容器未找到' });
                                return;
                            }
                            
                            // 获取容器在页面中的位置
                            const containerRect = drawerContainer.getBoundingClientRect();
                            const viewportHeight = window.innerHeight;
                            
                            // 找到footer元素（状态指示灯区域）
                            const footerElements = document.querySelectorAll('.row.mt-2');
                            let footerTop = viewportHeight; // 默认footer在视口底部
                            
                            // 查找最后一个row.mt-2元素（应该是状态指示灯区域）
                            if (footerElements.length > 0) {
                                const lastFooter = footerElements[footerElements.length - 1];
                                const footerRect = lastFooter.getBoundingClientRect();
                                footerTop = footerRect.top;
                            }
                            
                            // 计算LogDrawer应该占据的高度：从容器顶部到footer顶部-5px
                            // 同时确保高度不超过视口高度的90%，避免撑开页面
                            const availableHeight = Math.min(viewportHeight * 0.9, footerTop - containerRect.top - 5) - 10;
                            const finalHeight = Math.max(400, availableHeight);
                            
                            console.log('高度计算:', {
                                viewportHeight,
                                containerTop: containerRect.top,
                                containerBottom: containerRect.bottom,
                                footerTop: footerTop,
                                availableHeight: availableHeight,
                                finalHeight: finalHeight
                            });
                            
                            resolve({ 
                                height: finalHeight + 'px',
                                viewportHeight: viewportHeight,
                                containerTop: containerRect.top,
                                containerBottom: containerRect.bottom,
                                footerTop: footerTop
                            });
                        };
                        
                        // 如果DOM已经加载完成，立即计算
                        if (document.readyState === 'complete' || document.readyState === 'interactive') {
                            calculateHeight();
                        } else {
                            // 否则等待DOM加载完成
                            document.addEventListener('DOMContentLoaded', calculateHeight);
                        }
                    });
                })()
            ";

            var result = await JS.InvokeAsync<HeightResult>("eval", cts.Token, jsCode);

            LogWrapper.Information($"高度计算结果: viewportHeight={result.viewportHeight}, containerTop={result.containerTop}, containerBottom={result.containerBottom}, footerTop={result.footerTop}, finalHeight={result.height}");

            // 使用计算得到的高度
            calculatedHeight = result.height;

            // 通知UI更新
            await InvokeAsync(StateHasChanged);
        }
        catch (TaskCanceledException)
        {
            // JavaScript调用超时，使用默认高度
            LogWrapper.Warning("高度计算超时，使用默认高度600px");
            calculatedHeight = "600px";
        }
        catch (Exception ex)
        {
            // 如果计算失败，使用一个合理的默认高度
            LogWrapper.Error($"高度计算失败: {ex.Message}");
            calculatedHeight = "600px";
        }
    }

    public void Dispose()
    {
        _timer?.Stop();
        _timer?.Dispose();
    }
}